﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using WpfMesDemo2.Data;
using WpfMesDemo2.Models;

namespace WpfMesDemo2.ViewModels
{
    public class ProductionOrdersViewModel : ViewModelBase
    {
        private readonly MesRepository _repository;
        private ObservableCollection<ProductionOrder> _orders;
        private ProductionOrder _selectedOrder;
        private ObservableCollection<Product> _availableProducts;
        private Product _selectedProduct;
        private int _quantity;
        private string _statusMessage;

        public ObservableCollection<ProductionOrder> Orders
        {
            get => _orders;
            set => SetField(ref _orders, value);
        }

        public ProductionOrder SelectedOrder
        {
            get => _selectedOrder;
            set
            {
                SetField(ref _selectedOrder, value);
                OnPropertyChanged(nameof(CanEditOrder));
            }
        }

        public ObservableCollection<Product> AvailableProducts
        {
            get => _availableProducts;
            set => SetField(ref _availableProducts, value);
        }

        public Product SelectedProduct
        {
            get => _selectedProduct;
            set => SetField(ref _selectedProduct, value);
        }

        public int Quantity
        {
            get => _quantity;
            set => SetField(ref _quantity, value);
        }

        public string StatusMessage
        {
            get => _statusMessage;
            set => SetField(ref _statusMessage, value);
        }

        public bool CanEditOrder => SelectedOrder != null;

        public ICommand AddOrderCommand { get; }
        public ICommand DeleteOrderCommand { get; }
        public ICommand SaveOrderCommand { get; }
        public ICommand AddProductToOrderCommand { get; }
        public ICommand RemoveProductFromOrderCommand { get; }
        public ICommand RefreshOrdersCommand { get; }

        public ProductionOrdersViewModel()
        {
            _repository = new MesRepository();
            LoadOrders();
            LoadProducts();

            //AddOrderCommand = new RelayCommand(AddOrder);
            //DeleteOrderCommand = new RelayCommand(DeleteOrder, () => CanEditOrder);
            //SaveOrderCommand = new RelayCommand(SaveOrder, () => CanEditOrder);
            //AddProductToOrderCommand = new RelayCommand(AddProductToOrder,
            //    () => CanEditOrder && SelectedProduct != null && Quantity > 0);
            //RemoveProductFromOrderCommand = new RelayCommand(RemoveProductFromOrder,
            //    () => CanEditOrder && SelectedOrder?.Products?.Any() == true);
            //RefreshOrdersCommand = new RelayCommand(RefreshOrders);

            StatusMessage = "系统就绪";
        }

        private void LoadOrders()
        {
            try
            {
                StatusMessage = "正在加载订单数据...";
                Orders = new ObservableCollection<ProductionOrder>(_repository.GetAllOrders());
                StatusMessage = "订单数据加载完成";
            }
            catch (Exception ex)
            {
                StatusMessage = "加载订单数据失败: " + ex.Message;
                MessageBox.Show("加载订单数据时发生错误: " + ex.Message, "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void LoadProducts()
        {
            try
            {
                StatusMessage = "正在加载产品数据...";
                AvailableProducts = new ObservableCollection<Product>(_repository.GetAllProducts());
                StatusMessage = "产品数据加载完成";
            }
            catch (Exception ex)
            {
                StatusMessage = "加载产品数据失败: " + ex.Message;
                MessageBox.Show("加载产品数据时发生错误: " + ex.Message, "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void AddOrder()
        {
            try
            {
                var newOrder = new ProductionOrder
                {
                    OrderId = "ORD-" + DateTime.Now.ToString("yyyyMMddHHmmss"),
                    Customer = "新客户",
                    OrderDate = DateTime.Now,
                    DueDate = DateTime.Now.AddDays(7),
                    Status = "计划中",
                    Products = new ObservableCollection<Product>()
                };

                Orders.Add(newOrder);
                SelectedOrder = newOrder;
                StatusMessage = "新订单已创建";
            }
            catch (Exception ex)
            {
                StatusMessage = "创建订单失败: " + ex.Message;
                MessageBox.Show("创建订单时发生错误: " + ex.Message, "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void DeleteOrder()
        {
            if (SelectedOrder != null && MessageBox.Show(
                "确定要删除此订单吗？此操作不可撤销。",
                "确认删除",
                MessageBoxButton.YesNo,
                MessageBoxImage.Warning) == MessageBoxResult.Yes)
            {
                try
                {
                    _repository.DeleteOrder(SelectedOrder.Id);
                    Orders.Remove(SelectedOrder);
                    SelectedOrder = null;
                    StatusMessage = "订单已删除";
                }
                catch (Exception ex)
                {
                    StatusMessage = "删除订单失败: " + ex.Message;
                    MessageBox.Show("删除订单时发生错误: " + ex.Message, "错误",
                        MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }

        private void SaveOrder()
        {
            if (SelectedOrder != null)
            {
                try
                {
                    _repository.SaveOrder(SelectedOrder);
                    StatusMessage = "订单已保存";
                    MessageBox.Show("订单已成功保存到数据库", "成功",
                        MessageBoxButton.OK, MessageBoxImage.Information);
                    LoadOrders();
                }
                catch (Exception ex)
                {
                    StatusMessage = "保存订单失败: " + ex.Message;
                    MessageBox.Show("保存订单时发生错误: " + ex.Message, "错误",
                        MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }

        private void AddProductToOrder()
        {
            if (SelectedOrder != null && SelectedProduct != null && Quantity > 0)
            {
                try
                {
                    if (SelectedOrder.Products.Any(p => p.Id == SelectedProduct.Id))
                    {
                        StatusMessage = "此产品已添加到订单中";
                        MessageBox.Show("此产品已添加到订单中！", "提示",
                            MessageBoxButton.OK, MessageBoxImage.Information);
                        return;
                    }

                    var productToAdd = new Product
                    {
                        Id = SelectedProduct.Id,
                        ProductId = SelectedProduct.ProductId,
                        ProductName = SelectedProduct.ProductName,
                        Specification = SelectedProduct.Specification,
                        Quantity = Quantity,
                        ProductionDate = DateTime.Now,
                        ProductionLine = "生产线A",
                        Status = "计划中"
                    };

                    SelectedOrder.Products.Add(productToAdd);
                    Quantity = 0;
                    StatusMessage = "产品已添加到订单";
                }
                catch (Exception ex)
                {
                    StatusMessage = "添加产品失败: " + ex.Message;
                    MessageBox.Show("添加产品时发生错误: " + ex.Message, "错误",
                        MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }

        private void RemoveProductFromOrder()
        {
            if (SelectedOrder != null && SelectedOrder.Products.Any())
            {
                try
                {
                    var productToRemove = SelectedOrder.Products.FirstOrDefault();
                    if (productToRemove != null)
                    {
                        SelectedOrder.Products.Remove(productToRemove);
                        StatusMessage = "产品已从订单中移除";
                    }
                }
                catch (Exception ex)
                {
                    StatusMessage = "移除产品失败: " + ex.Message;
                    MessageBox.Show("移除产品时发生错误: " + ex.Message, "错误",
                        MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }

        private void RefreshOrders()
        {
            LoadOrders();
        }
    }
}
